package accs.model.io;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;

import accs.model.UserPasswordPair;

public class SimpleUserPasswordReader extends UserPasswordReader {
	private BufferedReader reader;
	private String delim=":";
	private String prefix="";
	
	public SimpleUserPasswordReader(Reader reader) {
		this(reader,":","");
	}
	
	public SimpleUserPasswordReader(Reader reader, String delim) {
		this(reader,delim,"");
	}
	
	public SimpleUserPasswordReader(Reader reader, String delim, String prefix) {
		this.reader=new BufferedReader(reader);
		this.delim=delim;
		this.prefix=prefix;
	}
	
	public SimpleUserPasswordReader(File file, String prefix) throws UnsupportedEncodingException, FileNotFoundException {
		this(new InputStreamReader(new FileInputStream(file),"utf-8"),prefix);
	}
	
	public UserPasswordPair read() throws IOException {
		String line=null;
		
		while((line=reader.readLine())!=null && (line.trim().isEmpty() || !line.startsWith(prefix))) {}
		if(line==null) return null;
		
		line=line.substring(prefix.length());
		int index=line.indexOf(delim);
		
		if(index==-1) {
			System.out.println("Error: "+line);
			return new UserPasswordPair(line,"");
		}
		
		String user=line.substring(0,index);
		String pass=line.substring(index+1);
		
		return new UserPasswordPair(user,pass);
	}
	
	public void close() throws IOException {
		reader.close();
	}
}